<?php

defined('BASEPATH') or die('forbidden');

/**
 * COOKIE类
 * @author  Karson
 * @name    cookie.php
 * @since   2012-7-3 14:26:59
 */
class Cookie {

    var $time;   //COOKIE有效时间
    var $prefix;  //COOKIE前缀
    var $domain;  //COOKIE有效域名

    function __construct() {
        $this->time = COOKIE_TIME;
        $this->prefix = COOKIE_PREFIX;
        $this->domain = COOKIE_DOMAIN;
    }

    /**
     * 获取COOKIE的值
     * @param string $name COOKIE的名称
     * @param string $data COOKIE的数据
     * @param int $time COOKIE有效时间，默认为null,即使用常量中配置的时间，如果为0即关闭浏览器失效
     * @param string $path COOKIE有效的目录，默认为/
     * @return bool 成功返回true,失败返回false
     */
    function set($name, $data, $time = null, $path = '/') {
        $time = is_null($time) ? $this->time : intval($time);
        if ($name != '') {
            $mname = $this->prefix . $name;
            $mdata = $data != '' ? substr(md5($data), 0, 16) : '';
            if ($data == '') {
                $time = time() - 86400;
            } else if ($time == 0) {
                $time = 0;
            } else {
                $time = time() + $time;
            }
            setcookie($name, $data, $time, $path, $this->domain);
            setcookie($mname, $mdata, $time, $path, $this->domain);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取COOKIE的值
     * @param string $name COOKIE的名称
     * @return bool 成功为true，失败为false
     */
    function get($name) {
        if (isset($_COOKIE[$name]) && isset($_COOKIE[$this->prefix . $name])) {
            if (!isset($_COOKIE[$this->prefix . $name]))
                return false;
            return (substr(md5($_COOKIE[$name]), 0, 16) != $_COOKIE[$this->prefix . $name]) ? '' : $_COOKIE[$name];
        }else {
            return false;
        }
    }

    /**
     * 清除COOKIE
     * @param string $name COOKIE的名称
     * @return bool 成功为true，失败为false
     */
    function clear($name, $path = '/') {
        if ($name != '') {
            $expire = time() - 360000;
            $this->set($name, '', $expire, $path, $this->domain);
            return true;
        } else {
            return false;
        }
    }

}